package com.mall507.fivepeaks.activity.main;

import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.hzh.frame.comn.callback.HttpCallBack;
import com.hzh.frame.core.HttpFrame.BaseHttp;
import com.hzh.frame.ui.fragment.BaseFM;
import com.hzh.frame.util.StatusBarUtil;
import com.hzh.frame.widget.rxbus.MsgEvent;
import com.hzh.frame.widget.rxbus.RxBus;
import com.hzh.frame.widget.xlistview.XListViewFooter;
import com.hzh.frame.widget.xrefresh.XSwipeRefreshLayout;
import com.mall507.comn.model.Original;
import com.mall507.fivepeaks.R;
import com.mall507.fivepeaks.comn.adapter.MainInfoAdapter;
import com.mall507.fivepeaks.comn.adapter.ShopMainAdapter;
import com.mall507.fivepeaks.comn.gsonBean.ShopMainJsonBean;
import com.mall507.fivepeaks.comn.itemDecoration.ShopMainItemDecoration;
import com.mall507.fivepeaks.util.Util;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;

/**
 * 商城首页
 */
public class MainRFM extends BaseFM implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {

    public static final String TAG="MainRFM";
    View baseView;
    XSwipeRefreshLayout swipeRefresh;
    RecyclerView recyclerView;
    private ImageView goTop;
    private int[] pageInfo = new int[]{1, 1, 20};//int[0]:起始页码;int[1]:当前页码 ;int[2]:每页显示数
    private ShopMainAdapter adapter;
//    private MainInfoAdapter adapter;
    private int itemSize = 0;

    @Override
    protected void onCreateBase() {
        baseView = setContentView(R.layout.fm_rv_main_index);
        getTitleView().addView(StatusBarUtil.createStatusBarView(getActivity(), ContextCompat.getColor(getActivity(), R.color.application_color)), 0);
        getTitleView().setLeftIsShow(false);
        getTitleView().setContent("首页");
        goTop = baseView.findViewById(R.id.goTop);
        goTop.setOnClickListener(this);
        swipeRefresh = baseView.findViewById(R.id.swipeRefresh);
        swipeRefresh.setColorSchemeResources(R.color.base_color);
        swipeRefresh.setOnRefreshListener(this);
        recyclerView = baseView.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 4, GridLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new ShopMainItemDecoration(Util.dip2px(getContext(), 3)));
        recyclerView.addOnScrollListener(new MyOnScrollListener());
        //初始化下拉刷新动画
        swipeRefresh.setProgressViewOffset(false, 0, 100);
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(true);
                onRefresh();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.goTop:
                recyclerView.scrollToPosition(0);
                break;
        }
    }

    @Override
    public void onRefresh() {
        pageInfo[1] = pageInfo[0];
        loadNetWorkData();
    }

    //请求网络数据
    public void loadNetWorkData() {
        JSONObject params=new JSONObject();
        try {
            params.put("page", pageInfo[1]);
            params.put("limit", pageInfo[2]);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        BaseHttp.getInstance().query("Floor/getFloor",params, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                ShopMainJsonBean jsonBean = new Gson().fromJson(response.toString(), ShopMainJsonBean.class);
                itemSize = jsonBean.count;
                loadView(jsonBean.data);
                swipeRefresh.setRefreshing(false);
            }
        });
    }

    //加载页面
    public void loadView(List<ShopMainJsonBean.ItemInfoListBean> listBean) {
        if (listBean != null && listBean.size() > 0) {
            if (pageInfo[0] == pageInfo[1]) {
                //下拉刷新 | 这里的listBean是下拉刷新出来的数据 | 包括loadHead数据
                if (adapter == null) {
                    adapter = new ShopMainAdapter(getActivity(), listBean);
//                    adapter = new MainInfoAdapter(getActivity(), listBean);
                    if (itemSize > 0 && itemSize >= pageInfo[2]) {
                        adapter.setFooterView(createFooterView());
                    } else {
                        adapter.removeFooterView();
                    }
                    recyclerView.setAdapter(adapter);
                } else {
                    if (itemSize > 0 && itemSize >= pageInfo[2]) {
                        adapter.setFooterView(createFooterView());
                    } else {
                        adapter.removeFooterView();
                    }
                    adapter.setDatas(listBean);
                }
                swipeRefresh.setRefreshing(false);
            } else {
                //加载更多 | 这里的listBean是加载更多出来的数据 | 不包括loadHead数据
                adapter.getDatas().addAll(listBean);
                if (adapter.getFooterView() != null) {
                    adapter.getFooterView().setClickable(true);
                    ((XListViewFooter) adapter.getFooterView()).setState(XListViewFooter.STATE_NORMAL);
                }
                if (listBean.size() < pageInfo[2]) {
                    adapter.removeFooterView();
                    //这里隐藏了footerView,会导致adapter.getItemCount()查询出来的总数少1,为保证数据一致所以这里+1
                    adapter.notifyItemRangeInserted(adapter.getItemCount() - listBean.size() + 1, listBean.size());
                } else {
                    //批量添加刷新从positionStart开始itemCount数量的item了（这里的刷新指回调onBindViewHolder()方法）
                    adapter.notifyItemRangeInserted(adapter.getItemCount() - listBean.size(), listBean.size());
                }
            }
        } else {
            closeLoadingAll();
        }
    }

    //关闭所有加载中状态View
    public void closeLoadingAll() {
        //关闭下拉刷新
        swipeRefresh.setRefreshing(false);
        //关闭加载更多
        if (adapter != null && adapter.getFooterView() != null) {
            adapter.removeFooterView();
        }
    }


    /**
     * 创建脚布局
     */
    public XListViewFooter createFooterView() {
        XListViewFooter mFooterView = new XListViewFooter(getActivity());
        mFooterView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
        mFooterView.setState(XListViewFooter.STATE_NORMAL);//设置加载更多状态
        mFooterView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.white));
        mFooterView.setClickable(true);
        mFooterView.setOnClickListener(new View.OnClickListener() {//绑定脚监听
            @Override
            public void onClick(View view) {
                //保证多次响应只响应一次
                if (adapter.getFooterView().isClickable()) {
                    view.setClickable(false);
                    ((XListViewFooter) view).setState(XListViewFooter.STATE_LOADING);
                    pageInfo[1]++;
//                    loadItem();
                    //onRefresh();
                }
            }
        });
        return mFooterView;
    }

    // RecyclerView的滑动监听事件
    private class MyOnScrollListener extends RecyclerView.OnScrollListener {
        /**
         * @param dx : 水平滚动距离
         * @param dy : 垂直滚动距离:每一次竖直滑动增量,不是位置, 向下为正 向上为负
         * @description 滚动时一直回调，直到停止滚动时才停止回调。单击时回调一次
         * @author 贺子航 2014-06-24 11:54
         */
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            GridLayoutManager layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
            int position = layoutManager.findFirstVisibleItemPosition();
            if (position <= 0) {
                View firstView = layoutManager.findViewByPosition(position);
                if (firstView.getTop() == 0) {
                    goTop.setVisibility(View.GONE);
                } else {
                    goTop.setVisibility(View.VISIBLE);
                }
            }
        }

        /**
         * SCROLL_STATE_IDLE表示当前并不处于滑动状态
         * SCROLL_STATE_DRAGGING表示当前RecyclerView处于滑动状态（手指在屏幕上）
         * SCROLL_STATE_SETTLING表示当前RecyclerView处于滑动状态，（手已经离开屏幕）
         */
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == RecyclerView.SCROLL_STATE_IDLE && isVisBottom(recyclerView)) {
                if (adapter.getFooterView() != null && adapter.getFooterView().getVisibility() == View.VISIBLE) {
                    adapter.getFooterView().performClick();
                }
            }
        }
    }

    //判断是否到达底部
    public static boolean isVisBottom(RecyclerView recyclerView) {
        GridLayoutManager layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
        //屏幕中最后一个可见子项的position
        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
        //当前屏幕所看到的子项个数
        int visibleItemCount = layoutManager.getChildCount();
        //当前RecyclerView的所有子项个数
        int totalItemCount = layoutManager.getItemCount();
        //RecyclerView的滑动状态
        int state = recyclerView.getScrollState();
        if (visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 && state == recyclerView.SCROLL_STATE_IDLE) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            //界面可见
            onRefresh();
        } else {
            //界面不可见 相当于onpause
        }
    }
}